﻿// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NUnit.Framework;

namespace Azure.ResourceManager.Monitor.Tests
{
    internal class DeduplicationCheck
    {
        private const string TestFrameworkAssembly = "Azure.ResourceManager.TestFramework";
        private const string AssemblyPrefix = "Azure.ResourceManager.";
        private const string TestAssemblySuffix = ".Tests";

        private const string AutoGeneratedSuffix = "AutoGenerated";

        [Test]
        public void ValidateNoDeduplicationInModels()
        {
            var testAssembly = Assembly.GetExecutingAssembly();
            var assemblyName = testAssembly.GetName().Name;
            Assert.IsTrue(assemblyName.EndsWith(TestAssemblySuffix), $"The test assembly should end with {TestAssemblySuffix}");
            var rpNamespace = assemblyName.Substring(0, assemblyName.Length - TestAssemblySuffix.Length);

            if (rpNamespace == TestFrameworkAssembly)
            {
                return;
            }

            TestContext.WriteLine($"Testing assembly {rpNamespace}");

            if (!rpNamespace.StartsWith(AssemblyPrefix))
            {
                return;
            }
            var sdkAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == rpNamespace) ?? Assembly.Load(rpNamespace);

            Assert.IsNotNull(sdkAssembly, $"The SDK assembly {rpNamespace} not found");

            // Verify if there is any class that ends with `AutoGenerated`
            List<string> errorList = new();

            foreach (var type in sdkAssembly.GetTypes())
            {
                if (type.IsClass && type.IsPublic)
                {
                    if (type.Name.EndsWith(AutoGeneratedSuffix))
                    {
                        errorList.Add(type.Name);
                    }
                }
            }

            Assert.IsEmpty(errorList, "DeduplicationCheck failed, the following types should be renamed because of the `lenient-model-deduplication` flag: \n" + string.Join(",", errorList) + "\nThis should be fixed via directives so that we no longer have them as duplicated schemas");
        }
    }
}
